<template>
    <a-modal :confirm-loading="modalOption.loading" :okText="modalOption.okText" @ok="modalOption.onOk"
             @cancel="modalOption.onCancel" :cancelText="modalOption.cancelText" :width="modalOption.width" :visible="visible"
             :title="modalOption.title">
        <div class="container">
            <a-form-model ref="formModel" :label-col="formOption.labelCol" :wrapper-col="formOption.wrapperCol"
                          :layout="formOption.layout" :label-align="formOption.labelAlign" :hide-required-mark="formOption.hideRequiredMark"
                          :rules="formOption.rules" :model="formOption.formData">
                <div class="tool-bar">
                   <a-card hoverable title="物料">
                       <a-row class="table">
                           <a-col class="col-h" :span="8">
                               <a-form-model-item label="物料名称" prop="name">
                                   <a-input :disabled="viewDetail" v-model="formOption.formData.name" placeholder="请输入物料名称" />
                               </a-form-model-item>
                           </a-col>
                           <a-col class="col-h" :span="8">
                               <a-form-model-item label="物料代码" prop="code">
                                   <a-input :disabled="viewDetail" v-model="formOption.formData.code" placeholder="请输入物料代码" />
                               </a-form-model-item>
                           </a-col>
<!--                           <a-col class="col-h" :span="8">-->
<!--                               <a-form-model-item label="标准" prop="standard">-->
<!--                                   <a-select :disabled="viewDetail" v-model="formOption.formData.standard" placeholder="请选择标准">-->
<!--                                       <a-select-option value="国标">国标</a-select-option>-->
<!--                                       <a-select-option value="省标">省标</a-select-option>-->
<!--                                       <a-select-option value="省标-北京">省标-北京</a-select-option>-->
<!--                                       <a-select-option value="省标-上海">省标-上海</a-select-option>-->
<!--                                       &lt;!&ndash;                                        <a-select-option value="国标-北京">国标-北京</a-select-option>&ndash;&gt;-->
<!--                                   </a-select>-->
<!--                               </a-form-model-item>-->
<!--                           </a-col>-->

                       </a-row>
                       <a-row class="table">
                           <a-col class="col-h" :span="8">
                               <a-form-model-item label="物料类别" prop="type">
                                   <a-select disabled v-model="formOption.formData.type" placeholder="请选择物料类别">
                                       <a-select-option value="原料">原料</a-select-option>
                                       <a-select-option value="其他">其他</a-select-option>
                                   </a-select>
                               </a-form-model-item>
                           </a-col>
                           <a-col class="col-h" :span="8">
                               <a-form-model-item label="物料分类" prop="materialType">
                                   <a-select disabled v-model="formOption.formData.materialType" placeholder="请选择物料分类">
                                       <a-select-option value="中药材">中药材</a-select-option>
                                       <a-select-option value="辅料">辅料</a-select-option>
                                       <a-select-option value="其他">其他</a-select-option>
                                   </a-select>
                               </a-form-model-item>
                           </a-col>
<!--                           <a-col class="col-h" :span="8">-->
<!--                               <a-form-model-item label="有效期至" prop="validDay">-->
<!--                                   <a-input :disabled="viewDetail" v-model="formOption.formData.validDay" placeholder="请输入有效期" suffix="月"/>-->
<!--                               </a-form-model-item>-->
<!--                           </a-col>-->
                       </a-row>
                       <a-row class="table">
                           <a-col class="col-h" :span="8">
                               <a-form-model-item label="状态" prop="state">
                                   <a-radio-group :disabled="viewDetail" v-model="formOption.formData.state">
                                       <a-radio :value="true">启用</a-radio>
                                       <a-radio :value="false">禁用</a-radio>
                                   </a-radio-group>
                               </a-form-model-item>
                           </a-col>
                           <a-col class="col-h" :span="8">
                               <a-form-model-item label="药材备注" prop="notice">
                                   <a-input :disabled="viewDetail" v-model="formOption.formData.notice"></a-input>
                               </a-form-model-item>
                           </a-col>
                           <a-col v-if="rowKey!=='辅料'" :span="8">
                               <template v-for="(item,idx) in addrList">
                                   <template>
                                       <a-form-model-item :wrapper-col="{style:{width:'300px'}}" :label="'产地'+(idx+1)" prop="prodAddress" :key="'addr_'+idx">
                                           <a-input :disabled="viewDetail" style="width: 127px;margin-right: 5px"  v-model="addrList[idx].value" placeholder="请输入产地" />
                                           <a-button v-if="idx == 0" :disabled="viewDetail" type="primary" @click="addAddr">新增产地</a-button>
                                           <a-icon v-if="idx != 0" v-show="!viewDetail" class="c-danger" type="delete" @click="removeAddr(idx)" style="margin-left:5px" />
                                       </a-form-model-item>
                                   </template>
                               </template>
                           </a-col>
                       </a-row>
                       <a-row class="table">
                           <a-col  class="col-h" :span="8">
                               <a-form-model-item label="复验期(月)" prop="reInspection">
                                   <a-input-number style="width: 220px" :disabled="viewDetail" v-model="formOption.formData.reInspection" placeholder="请输入复验期(月)"/>
                               </a-form-model-item>
                           </a-col>
                           <a-col  class="col-h" :span="8">
                               <a-form-model-item label="复验期提醒数/天" prop="reInspectionNoticeDay">
                                   <a-input-number style="width: 220px" :disabled="viewDetail" v-model="formOption.formData.reInspectionNoticeDay" placeholder="请输入复验期提醒天数/天" />
                               </a-form-model-item>
                           </a-col>
                           <a-col  class="col-h" :span="8">
                               <a-form-model-item label="有效期" prop="validDay">
                                   <a-input-number style="width: 220px" :disabled="viewDetail" v-model="formOption.formData.validDay" placeholder="请输入有效期" />
                               </a-form-model-item>
                           </a-col>
                       </a-row>
                       <a-row class="table" v-for="(item,i) in formOption.formData.stockConfig" :key="i">
                           <a-col :span="6">
                               <a-form-model-item label="库存区间" prop="stockConfig">
                                   <a-input-group compact>
                                       <a-input-number :disabled="viewDetail" :min="0" v-model="item.start"/>
                                       <a-input-number placeholder="~" style=" width: 31px; border-left: 0; pointer-events: none; backgroundColor: #fff" />
                                       <a-input-number :disabled="viewDetail" style="border-left: 0" :min="0" v-model="item.end"/>
                                   </a-input-group>
                               </a-form-model-item>
                               <span style="line-height: 40px">kg</span>
                           </a-col>
                           <a-col :span="18">
                               <span :style="{color:item.level === '高' ? '#F76A4A':item.level === '中' ? '#FFA842':'#22B585',}" style="line-height: 40px;">紧急程度：{{item.level}}</span>
                           </a-col>
                       </a-row>
                   </a-card>
                </div>
            </a-form-model>
        </div>
    </a-modal>
</template>
<script lang="ts">
import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import nextApi from "@/api/nextApi";

@Component({
    name: "addOrEdit",
    components: {
        Upload: () => import("@/components/upload.vue"),
    },
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: "" }) editId!: string;
    @Prop({ default: "" }) rowKey!: string;
    @Prop({default: false}) viewDetail!: boolean;
    @Watch("visible")
    visibleChange(val) {
        if (val) {
            setTimeout(()=>{
                this.modalOption.pageReady = true
                this.formOption.formData.materialType = this.rowKey
                if(this.rowKey === '其他'){
                    this.formOption.formData.type = '其他'
                }
            },500)
        }else{
            this.modalOption.pageReady = false
            this.modalOption.title = "新增";
            (this.$refs.formModel as any).resetFields();
            this.formOption.formData = {
                reInspection:'',//12.2新加字段复验期
                reInspectionNoticeDay:'',//12.2新加字段复验期提醒天数
                name: "",
                code: "",
                materialType: "",
                type: "原料",
                validDay: "",
                notice:'',
                img: "",
                state: true,
                standard:"国标",
                stockConfig:[
                    {
                        start: "",
                        end: "",
                        level: "高",
                    },
                    {
                        start: "",
                        end: "",
                        level: "中",
                    },
                    {
                        start: "",
                        end: "",
                        level: "低",
                    },
                ],
                prodAddress:[],
            }
            this.addrList = [{value:''}]
        }
    }
    @Watch("editId")
    editIdChange(val) {
        if (val) {
            console.log(this.viewDetail)
            if(val && this.viewDetail){
                this.modalOption.title = "详情";
            }else{
                this.modalOption.title = "编辑";
            }
            //查询当前id的数据
            this.getInfo()
        }
    }
    //组件配置
    modalOption: any = {
        pageReady:false,
        width: "90%",
        title: "新增",
        okText: "保存",
        cancelText: "取消",
        loading: false,
        onOk: () => {
            this.modalOk();
        },
        onCancel: () => {
            this.closeModal();
        },
    };
    //表单数据源

    //表单配置
    formOption: any = {
        labelCol: { style: { width: "120px" } },
        wrapperCol: { style: { width: "220px" } },
        layout: "inline",
        labelAlign: "right",
        hideRequiredMark: false,
        formData: {
            reInspection:'',//12.2新加字段复验期
            reInspectionNoticeDay:'',//12.2新加字段复验期提醒天数
            name: "",
            code: "",
            materialType: "",
            type: "原料",
            notice:'',
            validDay: "",
            img: "",
            state: true,
            standard:"国标",
            stockConfig:[
                {
                    start: "",
                    end: "",
                    level: "高",
                },
                {
                    start: "",
                    end: "",
                    level: "中",
                },
                {
                    start: "",
                    end: "",
                    level: "低",
                },
            ]
        },
        rules: {
            name: [{ required: true, message: "请输入名称", trigger: "blur" }],
            code: [{ required: true, message: "请输入编码", trigger: "blur" }],
            type: [{ required: true, message: "请选择大类", trigger: "change" }],
            validDay: [{ required: true, message: "请输入有效期", trigger: "blur" }],
            img: [{ required: true, message: "请上传图片", trigger: "change" }],
            materialType: [{ required: true, message: "请选择物料分类", trigger: "change" }],
            // stockConfig: [
            //     {
            //         required: true,
            //         validator: (rule, value, callback) => {
            //             value.forEach(item=>{
            //                 if(item.start && item.end){
            //                     return callback()
            //                 }else{
            //                     return callback(new Error('请完善库存区间'))
            //                 }
            //             })
            //         },
            //         trigger: "change",
            //     },
            // ],
        },
    };
    modalOk(){
        (this.$refs.formModel as any).validate(async (valid: boolean) => {
            if (!valid) return;
            this.modalOption.loading = true;
           try {
               //检查对象中的value是否为空，如果为空则删除
               this.addrList.forEach((item,index)=>{
                   if(index !== 0 && item.value == ""){
                        this.addrList.splice(index,1)
                   }
               })
               this.formOption.formData.prodAddress = this.addrList
               console.log('表单数据：',this.formOption.formData)
               let params = JSON.stringify(this.formOption.formData)
               let temp = JSON.parse(params)
               temp.stockConfig = JSON.stringify(temp.stockConfig)
               temp.prodAddress = JSON.stringify(temp.prodAddress)
               console.log(temp)
              if(this.modalOption.title === "新增"){
                  this.formOption.formData.materialType = this.rowKey
                  const res = await nextApi.addMaterial(temp)
                  if(res.code === 200){
                      this.$message.success(res.msg)
                  }
              }else if(this.modalOption.title === "编辑"){
                  this.formOption.formData.materialType = this.rowKey
                  const res = await nextApi.editMaterial(temp)
                  if(res.code === 200){
                      this.$message.success(res.msg)
                  }
              }

           }finally {
               this.modalOption.loading = false;
               this.closeModal();
           }
        })
    }
    /**
     * @description 处理一些数据的方法
     *  **/
    addrList: any[] = [{value: ""}];
    addAddr() {
        this.addrList.push({value: ""});
    }
    removeAddr(idx: number) {
        this.addrList.splice(idx, 1);
    }
    async getInfo(){
        const res = await nextApi.selectDetailById({id:this.editId})
        this.formOption.formData = res.data
        if(this.formOption.formData.prodAddress){
            this.formOption.formData.prodAddress = JSON.parse(res.data.prodAddress)
            this.addrList = this.formOption.formData.prodAddress
        }else{
            this.addrList = [{value: ""}]
        }

        if(this.formOption.formData.stockConfig !== ""){
            this.formOption.formData.stockConfig = JSON.parse(res.data.stockConfig)
            if(this.formOption.formData.stockConfig.length === 0){
                this.formOption.formData.stockConfig = [
                    {
                        start: "",
                        end: "",
                        level: "高",
                    },
                    {
                        start: "",
                        end: "",
                        level: "中",
                    },
                    {
                        start: "",
                        end: "",
                        level: "低",
                    },
                ]
            }
        }

    }
    closeModal() {
        this.$emit("closeModal");
    }
}
</script>
<style scoped lang="scss">
.container {
    padding: 0px;
    .MR-10 {
        margin-right: 10px;
    }
    .inputs {
        width: 200px;
    }
    .tool-bar {
        margin-bottom: 20px;

    }
    .table {
        margin-top: 20px;
    }
    .col-h{
        height: 2.4rem;
    }
}
</style>
